<template>

  <div>
    <div class="margin-container-list">
      <!--商品状态 -->
      <div class="tab-style-default">
        <el-tabs v-model="auditType" @tab-click="goodsStatusClick">
          <el-tab-pane label="待提交" name="0"></el-tab-pane>
          <el-tab-pane label="审核中" name="1"></el-tab-pane>
          <el-tab-pane label="审核通过" name="2"></el-tab-pane>
          <el-tab-pane label="审核未通过" name="3"></el-tab-pane>
          <el-tab-pane label="已售空" name="4"></el-tab-pane>
          <el-tab-pane label="全部已提交" name="5"></el-tab-pane>
        </el-tabs>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate">
        <div class="search-item">
          <el-select class="select-class" v-model="textCol" style="width: 120px">
            <el-option label="商品名称" value="title"></el-option>
            <el-option label="商品货号" value="goodsArticleNo"></el-option>
            <el-option label="商品条码" value="goodsBarCode"></el-option>
            <el-option label="外部编码" value="externalCode"></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model="textValue" placeholder="请输入关键词"></el-input>
          <el-select class="default-input" clearable v-model="defaultQuery.brandId" placeholder="请选择商品品牌">
            <el-option v-for="item in listBrands" :key="item.brandId" :label="item.brandName" :value="item.brandId">
            </el-option>
          </el-select>
          <el-cascader v-model="categoryIds" 
            :props="{ checkStrictly: true }" 
            change-on-select 
            placeholder="选择商品分类"
            :options="categoryData" 
            class="default-input" 
            clearable>
          </el-cascader>
          <!--<el-select class="select-class" v-model="searchListQuery.goodsStatus" style="width: 150px" placeholder="选择上下架状态">-->
          <!--<el-option label="全部" value="2"></el-option>-->
          <!--<el-option label="下架" value="0"></el-option>-->
          <!--<el-option label="上架" value="1"></el-option>-->
          <!--</el-select>-->
          <el-select v-model="defaultQuery.crossBorderType" placeholder="请选择跨境类型" clearable
            v-if="enterpriseConfig.crossBorderBusinessFlag === 1">
            <el-option label="全部" value=""></el-option>
            <template v-for="(val, key) in dict.crossBorderType">
              <el-option :label="val" :key="key" :value="key"></el-option>
            </template>
          </el-select>
          <el-date-picker v-if="auditType === '1'" 
            v-model="starEndTime" 
            type="daterange" 
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss" 
            start-placeholder="提交审核开始日期" 
            end-placeholder="提交审核结束日期">
          </el-date-picker>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
      <div v-if="getSupplierId() != ''" class="mar-b-10 mar-t-10">
        <el-button type="primary" @click="handleEdit" v-if="auditType === '0'">添加商品</el-button>
        <!-- <el-upload style="display: inline-block; margin-left: 10px;" action="/api/goods/supplierGoods/uploadTaoBaoZip"
          :before-upload="beforeZipUpload" name="files" v-loading="fileLoading" :data="uploadParams"
          :show-file-list="false" :on-success="handleUploadZipSuccess">
          <el-button type="primary">导入淘宝商品</el-button>
        </el-upload> -->
        <el-button type="primary" @click="openImportGoods">批量导入商品</el-button>
        <el-button class="batch-btn" v-if="auditType === '0'" @click="openBatchSetGoodsCategory">批量设置分类</el-button>
        <el-button class="batch-btn" v-if="enterpriseConfig.crossBorderBusinessFlag === 1 && auditType === '0'"
          @click="openBatchSetGoodsCustomsGoodsCode">批量设置海关编码
        </el-button>
        <el-button type="primary" @click="doSyncSupplierGoodsByDockingSystem()">同步供应商商品</el-button>
        <!--<el-button type="primary" plain @click="updateBatchAuditType('')" v-if="auditType === '0'">批量提交企业库</el-button>-->
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="goodsList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中">

          <el-table-column width="50px" type="selection" fixed="left"></el-table-column>
          <el-table-column width="280px" label="商品" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label><img :src="scope.row.mainImage" class="user-avatar"></label>
                <div class="font-14 pad-l-10">
                  <div v-if="scope.row.title.length <= 20">{{scope.row.title}}</div>
                  <div v-if="scope.row.title.length > 20">{{scope.row.title.slice(0,20) + '...'}}</div>
                  <template v-if="scope.row.categoryName">
                    <span class="category-style">[{{scope.row.categoryName}}]</span><br />
                    <el-tag size="mini" v-if="scope.row.skuFlag == 1" effect="light">多规格</el-tag>
                  </template>
                  <template v-if="scope.row.crossBorderType === 2">
                    <el-tag size="mini" effect="light">保</el-tag>
                  </template>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="商品货号" prop="goodsArticleNo"></el-table-column>
          <el-table-column width="150px" label="供应价">
            <template slot-scope="scope" v-if="scope.row.supplyPrice">
              ￥{{scope.row.supplyPrice}}
            </template>
          </el-table-column>
          <el-table-column width="150px" label="划线价">
            <template slot-scope="scope" v-if="scope.row.scribingPrice && scope.row.scribingPrice != '0.00'">
              ￥{{scope.row.scribingPrice}}
            </template>
          </el-table-column>
          <el-table-column width="150px" label="运费" prop="supplierPostFee"></el-table-column>
          <el-table-column width="150px" label="库存" prop="stock"></el-table-column>
          <el-table-column width="150px" label="销量">
            <template slot-scope="scope">
              <span v-if="auditType != 0">{{scope.row.salesNum}}</span>
            </template>
          </el-table-column>
          <el-table-column width="160px" label="提交审核时间">
            <template slot-scope="scope">
              <span v-if="auditType != 0">{{scope.row.auditTime}}</span>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="审核状态">
            <template slot-scope="scope">
              <template v-if="scope.row.auditType == '3'">
                <el-tooltip class="item" effect="dark" :content="scope.row.reject" placement="top-end">
                  <span style="color: #2d8cf0">{{ dict.auditType[scope.row.auditType]}}</span>
                </el-tooltip>
              </template>
              <template v-else>
                <span>{{ dict.auditType[scope.row.auditType]}}</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="上下架状态" v-if="auditType != '0'">
            <template slot-scope="scope">
              <template v-if="auditType == '4'">
                已售空
              </template>
              <template v-else>
                {{ dict.upDwonStatusFlag[scope.row.goodsStatus]}}
              </template>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="操作" align="right" fixed="right" v-show="getSupplierId() != ''">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="handleEdit(scope.row)"
                v-if="scope.row.auditType == '0' || scope.row.auditType == '2' || scope.row.auditType == '3'">编辑
              </el-button>
              <el-button type="text" size="medium" @click="handleSee(scope.row)" v-if="scope.row.auditType == '1'">查看详情
              </el-button>
              <el-button type="text" size="medium" @click="updateBatchAuditType(scope.row)"
                v-if="scope.row.auditType == '2' || scope.row.auditType == '3'">提交修改</el-button>
              <el-button type="text" size="medium" @click="updateBatchAuditType(scope.row)"
                v-if="scope.row.auditType == '0'">提交企业库</el-button>
              <el-button type="text" size="medium" @click="updateWithdrawAuditType(scope.row)"
                v-if="scope.row.auditType == '1'">撤回审核</el-button>
              <el-button type="text" size="medium" @click="updateStock(scope.row)"
                v-if="showEditStock && [2,3,4].includes(scope.row.auditType) && scope.row.crossBorderType !== 2">修改库存
              </el-button>
              <el-button type="text" size="medium" @click="handleDelete(scope.row)" v-if="scope.row.auditType == '0'">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" 
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!--修改库存-->
    <el-dialog title="" :visible.sync="skuStockVisible" :close-on-press-escape="true" class="payment-box">
      <el-form :model="form" label-width="0px" :rules="rules" ref="form" style="margin-top: -12px;">
        <el-form-item label="" class="one-label">
          <el-form-item label="" label-width="0px">
            <div class="table-container pad-t-20 pad-b-20">
              <div
                class="el-table el-table--fit el-table--border el-table--enable-row-hover el-table--medium el-table--scrollable-x">
                <div class="el-table__body-wrapper">
                  <table cellspacing="0" cellpadding="0" border="0" class="el-table__body" style="width: 100%;">
                    <thead class="el-table__header">
                      <tr>
                        <template v-for="(item, indexTh) in form.qualityData">
                          <th width="135" :key="indexTh">
                            <div class="cell text-align-c">{{ item.skuPropName }}</div>
                          </th>
                        </template>
                        <th width="135">
                          <div class="cell text-align-c">图片</div>
                        </th>
                        <th width="135">
                          <div class="cell text-align-c">供应价(元)</div>
                        </th>
                        <th width="135">
                          <div class="cell text-align-c">
                            <el-popover placement="top" width="160" v-model="visiblePopStock">
                              <div class="text-align-c pad-b-10">批量设置</div>
                              <el-form label-position="right" style='width: 100%;'>
                                <el-form-item>
                                  <el-input v-model="skuParamSettingValue"
                                    @keyup.native="skuParamSettingValue = checkInputPositiveNum(skuParamSettingValue)"
                                    type="number" />
                                </el-form-item>
                              </el-form>
                              <div class="mar-t--10" style="text-align: right;">
                                <el-button size="mini" type="text" @click="visiblePopStock = false">取消</el-button>
                                <el-button type="primary" size="mini" @click="batchUpdateSkuParamPrice">确定</el-button>
                              </div>
                              <label slot="reference" @click="editSkuParam('2')">
                                <span>库存</span>
                                <i class="el-icon-circle-plus mar-l-10 font-blue"></i>
                              </label>
                            </el-popover>
                          </div>
                        </th>
                        <th width="135">
                          <div class="cell text-align-c">条码</div>
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <!-- 规格为1个 -->
                      <template v-if="form.qualityData.length == 1">

                        <tr v-for="(item, index) in form.singleTable" :key="index">
                          <td>
                            <div class="cell text-align-c">
                              {{ item.skuPropValue }}
                            </div>
                          </td>

                          <td>
                            <div class="cell text-align-c">
                              <div>
                                <img v-if="item.imageUrl" :src="item.imageUrl" width="42px" height="42px"
                                  style="margin-left: -1px;margin-top: -1px;">
                                <i v-else class="el-icon-plus"></i>
                              </div>
                            </div>
                          </td>
                          <td>
                            <div class="cell">
                              {{item.supplyPrice}}
                            </div>
                          </td>
                          <td>
                            <div class="cell">
                              <el-input v-model="item.stock" @keyup.native="item.stock = checkInputNum(item.stock)"
                                placeholder="请输入库存"></el-input>
                            </div>
                          </td>
                          <td>
                            <div class="cell">
                              {{item.goodsBarCode}}
                            </div>
                          </td>
                        </tr>
                      </template>
                      <!-- 规格有2个以上 -->
                      <template v-else>
                        <tr v-for="(item, index) in form.qualityTable" :key="index">
                          <template v-for="(subItem, subIndex) in item">
                            <template v-if="subItem.skuPropId">
                              <td>
                                <div class="cell text-align-c">
                                  {{subItem.skuPropValue}}
                                </div>
                              </td>
                            </template>
                          </template>

                          <td>
                            <div class="cell text-align-c">
                              <div>
                                <img v-if="item.imageUrl" :src="item.imageUrl" width="42px" height="42px"
                                  style="margin-left: -1px;margin-top: -1px;">
                                <i v-else class="el-icon-plus"></i>
                              </div>
                            </div>
                          </td>
                          <td>
                            <div class="cell">
                              {{item.supplyPrice}}
                            </div>
                          </td>
                          <td>
                            <div class="cell">
                              <el-input v-model="item.stock" @keyup.native="item.stock = checkInputNum(item.stock)"
                                placeholder="请输入库存"></el-input>
                            </div>
                          </td>
                          <td>
                            <div class="cell">
                              {{item.goodsBarCode}}
                            </div>
                          </td>
                        </tr>
                      </template>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
        <div class="mar-t-10 mar-b-10 flex-center">
          <el-button type="primary" @click="saveDate">保存</el-button>
          <el-button @click="skuStockVisible = false">返回</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 批量设置海关编码弹窗 -->
    <BatchSetCustomsGoodsCode ref="batchSetCustomsGoodsCodeRef" :onSuccess="handleBatchSetCustomsGoodsCodeSuccessCall">
    </BatchSetCustomsGoodsCode>
    <!-- 批量设置分类弹窗 -->
    <BatchSetSupplierGoodsCategory ref="batchSetSupplierGoodsCategoryRef"
      :onSuccess="handleBatchSetGoodsCategorySuccessCall">
    </BatchSetSupplierGoodsCategory>
  </div>
</template>

<script>
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import {
    pageSupplierGoods,
    handleDelete,
    updateBatchAuditType,
    updateWithdrawAuditType,
    saveStock,
    getSupplierGoodsDetail,
    checkUploadTaoBaoZip,
    doSyncSupplierGoodsByDockingSystem
  } from '@/api/goods/supplierGoods'
  import {
    getBySupplierId
  } from '@/api/user/supplier-config'
  import {
    getDictByGroupName,
    getDictCommon
  } from '@/api/common/common'
  import {
    getToken
  } from '@/utils/auth'
  import elDragDialog from '@/directive/el-dragDialog'
  import {
    listBrand
  } from '@/api/user/enterpriseBrand'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  import BatchSetCustomsGoodsCode from '@/views/goods/components/batch-set-customs-goods-code'
  import BatchSetSupplierGoodsCategory from '@/views/goods/components/batch-set-supplier-goods-category'
  export default {
    directives: {
      elDragDialog
    },
    components: {
      BatchSetCustomsGoodsCode,
      BatchSetSupplierGoodsCategory
    },
    data() {
      return {
        total: null,
        multipleSelection: [],
        listLoading: true,
        skuStockVisible: false,
        starEndTime: [],
        listBrands: [],
        // 文本model
        textCol: 'title',
        textValue: '',
        // 默认查询表单
        defaultQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          supplierId: '',
          goodsStatus: '',
          title: '',
          brandId: '',
          crossBorderType: ''
        },
        // 查询表单
        searchListQuery: {},
        form: {
          skuFlag: '0',
          sellPrice: '',
          supplyPrice: '0',
          supplierPostFee: 0,
          distributeType: 1,
          distributeRatio: '',
          distributeFee: '',
          shareMemberRatio: '',
          shareMemberFee: '',
          levelOnePartnerRatio: '',
          levelOnePartnerFee: '',
          levelTwoPartnerRatio: '',
          levelTwoPartnerFee: '',
          recruiterRatio: '',
          recruiterFee: '',
          stock: '',
          goodsBarCode: '',
          stockWarn: '',
          scribingPrice: '',
          unrealSalesNum: '0',
          singleTable: [],
          qualityData: [{
            skuPropId: -1,
            skuPropName: '',
            skuPropValueList: [{
              skuPropValue: '',
              skuPropValueId: -2,
              skuPropId: -1,
              skuPropName: ''
            }]
          }],
          qualityTable: [],
          dataTable: []
        },
        supplierId: '',
        searchLabelType: '',
        dict: {},
        visiblePopStock: false,
        skuParamSettingValue: '',
        skuParamSettingLabel: '',
        auditType: '0',
        categoryIds: [],
        goodsList: [],
        comDict: {},
        categoryData: [],
        rules: {
          stock: [
            { max: 8, message: '库存最多8个字节' },
            { required: true, message: '请填写商品库存', trigger: 'blur' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请填写正确商品库存' }
          ]
        },
        uploadParams: '',
        fileLoading: '',
        uploadCheckId: '',
        supplierConfig: {},
        showEditStock: false,
        // 系统参数
        enterpriseConfig: {
          // 增值功能跨境业务
          crossBorderBusinessFlag: 0
        },
        clickSyncGoodsNum: 0
      }
    },
    // 初始化页面
    created() {
      this.searchListQuery = { ...this.defaultQuery }
      this.uploadParams = {
        accessToken: getToken(),
        enterpriseId: this.getEnterpriseId(),
        supplierId: this.getSupplierId()
      }
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.supplierId) {
        this.supplierId = queryParams.supplierId
      }
      if (queryParams && queryParams.currentPage) {
        this.searchListQuery.currentPage = queryParams.currentPage
      }
      if (queryParams && queryParams.auditType) {
        this.auditType = queryParams.auditType
      }
      getBySupplierId(this.getSupplierId()).then((response) => {
        if (response.isError) return
        this.supplierConfig = response.data
        if (this.supplierConfig.warehouseAuthority === 1 && this.supplierConfig.warehouseDeliverFlag === 1) {
          // 开启仓库库存，不允许编辑
          this.showEditStock = false
        } else {
          this.showEditStock = true
        }
      })
      this.initEnterpriseConfig()
      this.initDict()
      this.listBrand()
      this.listGoodsCategory()
      this.initGoodsList()
      this.initDictCommon()
    },
    mounted() {},
    methods: {
      listBrand() {
        listBrand(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.listBrands = response.data
        })
      },
      initDictCommon() {
        getDictCommon().then(response => {
          this.comDict = response.data
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initGoodsList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initGoodsList()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      initDict() {
        getDictByGroupName('SupplierGoodsDTO').then(response => {
          this.dict = response.data
        })
      },
      setSearchListQuery() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        const categoryIds = this.categoryIds
        this.searchListQuery.oneCategoryId = categoryIds.length > 0 ? categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = categoryIds.length > 1 ? categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = categoryIds.length > 2 ? categoryIds[2] : ''
        this.searchListQuery.labelType = this.searchLabelType
        if (this.searchListQuery.goodsStatus === '2') {
          this.searchListQuery.goodsStatus = ''
        }
        if (this.starEndTime && this.starEndTime.length > 0) {
          this.searchListQuery.startTime = this.starEndTime[0]
          this.searchListQuery.endTime = this.starEndTime[1]
        } else {
          this.searchListQuery.startTime = ''
          this.searchListQuery.endTime = ''
        }
        this.searchListQuery['auditType'] = this.auditType
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.supplierId = this.getSupplierId()
      },
      initGoodsList() {
        this.setSearchListQuery()
        this.listLoading = true
        pageSupplierGoods(this.searchListQuery).then(response => {
          if (response.isError) return
          this.listLoading = false
          this.total = response.data.total
          this.goodsList = response.data.records
          Object.assign(this.dict, response.data.dict)
        })
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      handleSearch() {
        this.initGoodsList()
      },
      resetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.categoryIds = originData.categoryIds
        this.defaultQuery = originData.defaultQuery
        this.initGoodsList()
      },
      // 商品状态
      goodsStatusClick() {
        this.handleSearch()
      },
      // 编辑
      handleEdit(row) {
        this.$router.push({
          path: '/goods/supplier-goods/edit/index',
          query: {
            supplierGoodsId: row.supplierGoodsId,
            currentPage: this.searchListQuery.currentPage.toString(),
            activeName: '1',
            auditType: this.auditType
          }
        })
      },
      handleSee(row) {
        this.$router.push({
          path: '/goods/supplier-goods/edit/index',
          query: {
            supplierGoodsId: row.supplierGoodsId,
            currentPage: this.searchListQuery.currentPage.toString(),
            activeName: '2',
            auditType: this.auditType
          }
        })
      },
      // 撤回审核
      updateWithdrawAuditType(row) {
        this.$confirm('商品正在等待企业审核，确定要撤回审核？', '提示', {
          confirmButtonText: '撤回审核',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateWithdrawAuditType(row.supplierGoodsId).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '成功'
            })
            this.initGoodsList()
          })
        })
      },
      // 同步供应商商品
      doSyncSupplierGoodsByDockingSystem() {
        if (this.clickSyncGoodsNum > 0) {
          this.$confirm('已点过同步商品，建议间隔1分钟以后，确定还要同步商品吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.doSyncSupplierGoodsByDockingSystemMethod()
          })
        } else {
          this.doSyncSupplierGoodsByDockingSystemMethod()
        }
      },
      doSyncSupplierGoodsByDockingSystemMethod() {
        doSyncSupplierGoodsByDockingSystem(this.getSupplierId(), this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.msgSuccess(response.msg)
          this.initGoodsList()
          this.clickSyncGoodsNum = this.clickSyncGoodsNum + 1
        })
      },
      // 修改库存
      updateStock(row) {
        if (row.skuFlag === 0) {
          this.$prompt('请输入库存', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^\+?[0-9]\d*$/,
            inputErrorMessage: '格式:大于等于0的整数'
          }).then(({
            value
          }) => {
            const obj = JSON.parse(JSON.stringify(row))
            obj.stock = value
            saveStock(obj).then(response => {
              if (response.isError) return
              this.$message({
                type: 'success',
                message: '成功'
              })
              this.initGoodsList()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            })
          })
        } else {
          getSupplierGoodsDetail(row.supplierGoodsId).then((response) => {
            if (response.isError) return
            this.form.supplierGoodsId = response.data.supplierGoodsId
            this.form.goodsImages = response.data.goodsImages
            this.form.supplierId = response.data.supplierId
            this.form.enterpriseId = response.data.enterpriseId
            this.form.goodsArticleNo = response.data.goodsArticleNo
            this.form.title = response.data.title
            this.form.unit = response.data.unit
            this.form.oneCategoryId = response.data.oneCategoryId
            this.form.twoCategoryId = response.data.twoCategoryId
            this.form.threeCategoryId = response.data.threeCategoryId
            const skuFlag = this.$utils.isExist(response.data.skuFlag) ? response.data.skuFlag + '' : '0'
            this.form.skuFlag = skuFlag
            this.form.supplyPrice = this.$utils.isExist(response.data.supplyPrice) ? response.data.supplyPrice : '0'
            this.form.stock = this.$utils.isExist(response.data.stock) ? response.data.stock + '' : ''
            this.form.goodsBarCode = this.$utils.isExist(response.data.goodsBarCode) ? response.data.goodsBarCode +
              '' : ''
            if (response.data.skuFlag === 1) {
              const qualityData = response.data.qualityData
              if (qualityData.length === 1) {
                const skuPropValueList = qualityData[0].skuPropValueList
                for (let i = 0; i < skuPropValueList.length; i++) {
                  skuPropValueList[i].imageUrl = ''
                  skuPropValueList[i].skuId = ''
                  skuPropValueList[i].price = ''
                  skuPropValueList[i].supplyPrice = ''
                  skuPropValueList[i].stock = ''
                  skuPropValueList[i].goodsBarCode = ''
                  skuPropValueList[i].warnStock = ''
                }
              }
              this.form.qualityData = qualityData
              this.form.dataTable = response.data.qualityTable
              this.qualityInit()
              this.setQualityTable(response.data.qualityTable)
            }
            this.skuStockVisible = true
          })
        }
      },
      // 删除
      handleDelete(row) {
        this.$confirm('此操作将删除该商品，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          handleDelete(row.supplierGoodsId).then(response => {
            if (response.isError) return
            this.initGoodsList()
          })
        })
      },
      // 提交审核
      updateBatchAuditType(row) {
        const array = []
        if (row !== '') {
          array.push(row.supplierGoodsId)
        } else {
          const selections = this.multipleSelection
          if (selections.length === 0) {
            this.$message({
              type: 'error',
              message: '请勾选商品!'
            })
            return
          }
          selections.forEach(e => {
            array.push(e.supplierGoodsId)
          })
        }
        const params = {
          supplierGoodsIds: array.join(','),
          supplierId: this.getSupplierId()
        }
        updateBatchAuditType(params).then(response => {
          if (response.isError) return
          this.$message({
            message: '成功提交',
            type: 'success'
          })
          this.initGoodsList()
        })
      },
      // 添加一级规格
      addQta() {
        const propId = this.getID()
        const valueId = this.getID()
        this.form.qualityData.push({
          skuPropId: propId,
          skuPropName: '',
          skuPropValueList: [{
            skuPropValue: '',
            skuPropValueId: valueId,
            skuPropId: propId,
            skuPropName: ''
          }]
        })
        this.qualityInit()
      },
      editSkuParam(type) {
        this.skuParamSettingType = type
        this.skuParamSettingValue = ''
        if (type === '1') {
          this.skuParamSettingLabel = '零售价'
        } else if (type === '2') {
          this.skuParamSettingLabel = '库存'
        } else if (type === '3') {
          this.skuParamSettingLabel = '供应价'
        }
      },
      // 数列展示
      qualityInit() {
        if (this.form.qualityData.length === 0) {
          this.addQta()
        }

        const arrQta = []
        const itemQta = this.form.qualityData
        if (itemQta.length === 1) {
          const skuPropId = itemQta[0].skuPropId
          const skuPropName = itemQta[0].skuPropName
          const skuPropValueList = itemQta[0].skuPropValueList
          for (let i = 0; i < skuPropValueList.length; i++) {
            skuPropValueList[i].skuPropId = skuPropId
            skuPropValueList[i].skuPropName = skuPropName
          }
          this.form.singleTable = skuPropValueList
        } else {
          const skuCache = {}
          if (this.form.qualityTable.length > 0) {
            this.form.qualityTable.forEach(row => {
              let item = skuCache
              for (const col in row) {
                if (row[col].skuPropValueId) {
                  if (!item[row[col].skuPropValueId]) {
                    item[row[col].skuPropValueId] = {
                      ...row
                    }
                  }
                  item = item[row[col].skuPropValueId]
                }
              }
            })
          }
          this.form.qualityTable = []
          for (let i = 0; i < itemQta.length; i++) {
            const skuPropId = itemQta[i].skuPropId
            const skuPropName = itemQta[i].skuPropName
            for (let j = 0; j < itemQta[i].skuPropValueList.length; j++) {
              itemQta[i].skuPropValueList[j].skuPropId = skuPropId
              itemQta[i].skuPropValueList[j].skuPropName = skuPropName
            }
            arrQta.push(itemQta[i].skuPropValueList)
          }
          this.form.qualityTable = this.$utils.descartes(arrQta)
          if (this.form.qualityTable.length > 0) {
            this.form.qualityTable.forEach((row, index) => {
              let item = skuCache
              for (const col in row) {
                if (row[col].skuPropValueId) {
                  if (item[row[col].skuPropValueId]) {
                    item = item[row[col].skuPropValueId]
                  }
                }
              }
              // 新增子规格，设置原来的sku的值
              if (item.supplierPrice) {
                this.$set(this.form.qualityTable[index], 'supplierPrice', item.supplierPrice)
              }
              if (item.goodsBarCode) {
                this.$set(this.form.qualityTable[index], 'goodsBarCode', item.goodsBarCode)
              }
              if (item.stock) {
                this.$set(this.form.qualityTable[index], 'stock', item.stock)
              }
              if (item.skuId) {
                this.$set(this.form.qualityTable[index], 'skuId', item.skuId)
              }
              if (item.imageUrl) {
                this.$set(this.form.qualityTable[index], 'imageUrl', item.imageUrl)
              }
            })
          }
        }
      },
      setQualityTable(dataTable) {
        const skuValueMap = new Map()
        for (let i = 0; i < dataTable.length; i++) {
          skuValueMap.set(dataTable[i].skuValueIds, dataTable[i])
        }

        const qualityTable = this.form.qualityTable
        const qualityData = this.form.qualityData

        if (qualityData.length === 1) {
          const skuPropValueList = qualityData[0].skuPropValueList
          const skuPropId = qualityData[0].skuPropId
          const skuPropName = qualityData[0].skuPropName

          for (let i = 0; i < skuPropValueList.length; i++) {
            skuPropValueList[i].skuPropId = skuPropId
            skuPropValueList[i].skuPropName = skuPropName
            const skuPropValueId = skuPropValueList[i].skuPropValueId
            const array = []
            array.push(skuPropValueId)
            const skuValueKey = array.sort().toString()
            const skuValueObj = skuValueMap.get(skuValueKey)
            skuPropValueList[i].imageUrl = this.$utils.isExist(skuValueObj.imageUrl) ? skuValueObj.imageUrl : ''
            skuPropValueList[i].price = this.$utils.isExist(skuValueObj.price) ? skuValueObj.price : ''
            skuPropValueList[i].supplyPrice = this.$utils.isExist(skuValueObj.supplyPrice) ? skuValueObj.supplyPrice : ''
            skuPropValueList[i].stock = this.$utils.isExist(skuValueObj.stock) ? skuValueObj.stock : ''
            skuPropValueList[i].goodsBarCode = this.$utils.isExist(skuValueObj.goodsBarCode) ? skuValueObj.goodsBarCode : ''
            skuPropValueList[i].warnStock = this.$utils.isExist(skuValueObj.warnStock) ? skuValueObj.warnStock : ''
          }

          this.form.singleTable = skuPropValueList
        } else {
          const array = []
          for (let i = 0; i < qualityTable.length; i++) {
            const item = qualityTable[i]
            const skuPropValueList = []
            for (const key in item) {
              if (this.$utils.isExist(item[key].skuPropId)) {
                const skuPropValueId = item[key].skuPropValueId
                skuPropValueList.push(skuPropValueId)
              }
            }

            const obj = {}
            const skuValueKey = skuPropValueList.sort().toString()
            const skuValueObj = skuValueMap.get(skuValueKey)
            if (skuValueObj != null) {
              for (const key in item) {
                obj[key] = item[key]
              }
              obj.imageUrl = this.$utils.isExist(skuValueObj.imageUrl) ? skuValueObj.imageUrl : ''
              obj.price = this.$utils.isExist(skuValueObj.price) ? skuValueObj.price : ''
              obj.supplyPrice = this.$utils.isExist(skuValueObj.supplyPrice) ? skuValueObj.supplyPrice : ''
              obj.stock = this.$utils.isExist(skuValueObj.stock) ? skuValueObj.stock : ''
              obj.skuId = this.$utils.isExist(skuValueObj.skuId) ? skuValueObj.skuId : ''
              obj.supplierPrice = this.$utils.isExist(skuValueObj.supplierPrice) ? skuValueObj.supplierPrice : ''
              obj.warnStock = this.$utils.isExist(skuValueObj.warnStock) ? skuValueObj.warnStock : ''
              array.push(obj)
            } else {
              console.log('sku异常' + skuValueKey)
            }
          }
          this.form.qualityTable = array
        }
      },
      // 批量更新sku价格，库存
      batchUpdateSkuParamPrice() {
        const paramValue = this.skuParamSettingValue
        const skuParamSettingType = this.skuParamSettingType
        const qualityData = this.form.qualityData
        if (qualityData.length === 1) {
          for (let i = 0; i < this.form.singleTable.length; i++) {
            if (skuParamSettingType === '1') {
              this.visiblePopPrice = false
              this.$set(this.form.singleTable[i], 'price', paramValue)
            } else if (skuParamSettingType === '3') {
              this.$set(this.form.singleTable[i], 'supplyPrice', paramValue)
            } else if (skuParamSettingType === '2') {
              this.visiblePopStock = false
              this.$set(this.form.singleTable[i], 'stock', paramValue)
            }
          }
        } else {
          const qualityTable = this.form.qualityTable
          for (let i = 0; i < qualityTable.length; i++) {
            if (skuParamSettingType === '1') {
              this.visiblePopPrice = false
              this.$set(this.form.qualityTable[i], 'price', paramValue)
            } else if (skuParamSettingType === '3') {
              this.$set(this.form.qualityTable[i], 'supplyPrice', paramValue)
            } else if (skuParamSettingType === '2') {
              this.visiblePopStock = false
              this.$set(this.form.qualityTable[i], 'stock', paramValue)
            }
          }
        }
      },
      getID(length) {
        const ids = this.ids
        const id = -parseInt(Math.round(Math.random() * 100000000))
        if (ids.indexOf(id) > 0) {
          this.getID()
        } else {
          ids.push(id)
          this.ids = ids
          return id
        }
      },
      saveDate() {
        const qualityData = this.form.qualityData
        const qualityTable = this.form.qualityTable
        const table = []
        if (qualityData.length === 1) {
          const skuPropId = qualityData[0].skuPropId
          const skuPropName = qualityData[0].skuPropName
          const singleTable = this.form.singleTable
          for (let i = 0; i < singleTable.length; i++) {
            const imageUrl = this.$utils.isExist(singleTable[i].imageUrl) ? singleTable[i].imageUrl : ''
            const price = this.$utils.isExist(singleTable[i].price) ? singleTable[i].price : ''
            const skuSupplyPrice = this.$utils.isExist(singleTable[i].supplyPrice) ? singleTable[i].supplyPrice : ''
            const goodsBarCode = this.$utils.isExist(singleTable[i].goodsBarCode) ? singleTable[i].goodsBarCode : ''
            const stock = this.$utils.isExist(singleTable[i].stock) ? singleTable[i].stock : ''
            const skuId = this.$utils.isExist(singleTable[i].skuId) ? singleTable[i].skuId : ''

            const skuPropValueId = singleTable[i].skuPropValueId
            const skuPropValue = singleTable[i].skuPropValue

            const projectGoodsSkuDTO = {}
            projectGoodsSkuDTO.imageUrl = imageUrl
            projectGoodsSkuDTO.price = price
            projectGoodsSkuDTO.supplyPrice = skuSupplyPrice
            projectGoodsSkuDTO.goodsBarCode = goodsBarCode
            projectGoodsSkuDTO.stock = stock
            projectGoodsSkuDTO.skuId = skuId
            const skuPropValueList = []
            const propValue = {
              skuPropId: skuPropId,
              skuPropName: skuPropName,
              skuPropValueId: skuPropValueId,
              skuPropValue: skuPropValue
            }
            skuPropValueList.push(propValue)
            projectGoodsSkuDTO.skuPropValueList = skuPropValueList
            table.push(projectGoodsSkuDTO)
          }
        } else {
          for (let i = 0; i < qualityTable.length; i++) {
            const projectGoodsSkuDTO = {}
            const item = qualityTable[i]
            projectGoodsSkuDTO.imageUrl = this.$utils.isExist(item['imageUrl']) ? item['imageUrl'] : ''
            projectGoodsSkuDTO.price = this.$utils.isExist(item['price']) ? item['price'] : ''
            projectGoodsSkuDTO.supplyPrice = this.$utils.isExist(item['supplyPrice']) ? item['supplyPrice'] : ''
            projectGoodsSkuDTO.stock = this.$utils.isExist(item['stock']) ? item['stock'] : ''
            projectGoodsSkuDTO.skuId = this.$utils.isExist(item['skuId']) ? item['skuId'] : ''
            projectGoodsSkuDTO.goodsBarCode = this.$utils.isExist(item['goodsBarCode']) ? item['goodsBarCode'] : ''
            const skuPropValueList = []
            for (const key in item) {
              if (this.$utils.isExist(item[key].skuPropId)) {
                const skuPropId = item[key].skuPropId
                const skuPropName = item[key].skuPropName
                const skuPropValue = item[key].skuPropValue
                const skuPropValueId = item[key].skuPropValueId
                const projectGoodsSkuPropValueDTO = {
                  skuPropId: skuPropId,
                  skuPropName: skuPropName,
                  skuPropValue: skuPropValue,
                  skuPropValueId: skuPropValueId
                }
                skuPropValueList.push(projectGoodsSkuPropValueDTO)
              }
            }
            projectGoodsSkuDTO.skuPropValueList = skuPropValueList
            table.push(projectGoodsSkuDTO)
          }
        }
        this.form.qualityData = qualityData
        this.form.qualityTable = table
        const data = {
          enterpriseId: this.form.enterpriseId,
          supplierGoodsId: this.form.supplierGoodsId,
          supplierId: this.getSupplierId(),
          title: this.form.title,
          unit: this.form.unit,
          goodsImages: this.form.goodsImages,
          oneCategoryId: this.form.oneCategoryId,
          twoCategoryId: this.form.twoCategoryId,
          threeCategoryId: this.form.threeCategoryId,
          skuFlag: this.form.skuFlag,
          supplyPrice: this.form.supplyPrice,
          stock: this.form.stock,
          supplierPostFee: this.form.supplierPostFee,
          goodsBarCode: this.form.goodsBarCode,
          goodsArticleNo: this.form.goodsArticleNo,
          qualityData: qualityData,
          qualityTable: table
        }
        // 排序
        this.isSubmit = true
        if (!this.isSubmit) {
          return
        }
        this.listLoading = true

        this.loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        saveStock(data).then((response) => {
          this.listLoading = false
          this.loading.close()
          if (response.isError) {
            // this.isSubmit = false
            return
          }
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.skuStockVisible = false
          this.initGoodsList()
        })
      },
      checkForm() {
        const distributeType = this.form.distributeType
        const supplyPrice = this.form.supplyPrice
        const skuFlag = this.form.skuFlag
        // 需要校验的集合
        const checkArrays = []
        if (skuFlag === '0') {
          checkArrays.push('supplyPrice')
          checkArrays.push('stock')
        }
        if (distributeType === 1) {
          checkArrays.push('distributeRatio')
        } else if (distributeType === 2) {
          checkArrays.push('distributeFee')
        }
        checkArrays.push('scribingPrice')
        checkArrays.push('unrealSalesNum')
        checkArrays.push('stockWarn')
        let ret = true
        let message = ''
        this.$refs.form.validateField(checkArrays, (valid) => {
          if (valid !== '') {
            message = valid
            ret = false
            return false
          }
        })
        if (!ret) {
          this.$message({
            type: 'error',
            message: message
          })
          return false
        }
        if (skuFlag === '0') {
          if (distributeType === 2 && this.form.distributeFee != null && (this.form.distributeFee * 1 >= supplyPrice *
              1)) {
            this.$message({
              type: 'error',
              message: '微客佣金不能大于商品金额'
            })
            return false
          }
          if (distributeType === 2) {
            const distributeFee = !this.form.distributeFee ? 0 : this.form.distributeFee * 1
            if (distributeFee > supplyPrice * 1) {
              this.$message({
                type: 'error',
                message: '微客佣金不能大于商品金额'
              })
              return false
            }
            const shareMemberFee = !this.form.shareMemberFee ? 0 : this.form.shareMemberFee * 1
            if (shareMemberFee > supplyPrice * 1) {
              this.$message({
                type: 'error',
                message: '微客佣金不能大于商品金额'
              })
              return false
            }
            if ((distributeFee + shareMemberFee) > supplyPrice * 1) {
              this.$message({
                type: 'error',
                message: '微客佣金+顾客分销佣金不能大于商品金额'
              })
              return false
            }
          }
        } else {
          // 校验属性名称是否相同
          const propNames = []
          const qualityData = this.form.qualityData
          for (let i = 0; i < qualityData.length; i++) {
            const skuPropName = qualityData[i].skuPropName
            if (!this.$utils.isExist(skuPropName)) {
              this.$message({
                type: 'error',
                message: '商品规格不能为空'
              })
              return false
            }
            const usePropValueList = []
            const skuPropValueList = qualityData[i].skuPropValueList
            for (let j = 0; j < skuPropValueList.length; j++) {
              const skuPropValue = skuPropValueList[j].skuPropValue
              if (!this.$utils.isExist(skuPropValue)) {
                this.$message({
                  type: 'error',
                  message: '商品属性不能为空'
                })
                return false
              }

              if (usePropValueList.indexOf(skuPropValue) !== -1) {
                this.$message({
                  type: 'error',
                  message: '同规格下属性名称"' + skuPropValue + '"重复'
                })
                return false
              } else {
                usePropValueList.push(skuPropValue)
              }
            }

            const propName = qualityData[i].skuPropName
            if (propNames.indexOf(propName) !== -1) {
              this.$message({
                type: 'error',
                message: '规格名称"' + propName + '"重复'
              })
              return false
            } else {
              propNames.push(propName)
            }
          }

          let table = []
          if (qualityData.length === 1) {
            const singleTable = this.form.singleTable
            table = singleTable
          } else {
            const qualityTable = this.form.qualityTable
            table = qualityTable
          }

          let stockTotal = 0
          for (let i = 0; i < table.length; i++) {
            const stock = table[i].stock
            const warnStock = table[i].warnStock
            stockTotal = stockTotal + stock

            if (!this.$utils.isExist(stock)) {
              this.$message({
                type: 'error',
                message: '商品库存不能为空'
              })
              return false
            }

            if (stock.length > 8) {
              this.$message({
                type: 'error',
                message: '商品库存长度不能超过8个字节'
              })
              return false
            }

            // 正则表达式校验
            if (this.$utils.isExist(warnStock)) {
              const reg3 = /^[0-9]*[1-9][0-9]*$/
              const pattern3 = new RegExp(reg3)
              if (!pattern3.test(warnStock)) {
                this.$message({
                  type: 'error',
                  message: '请正确输入预警库存'
                })
                return false
              }
            }
          }

          // 正则表达式校验
          const reg = /^[0-9]*[1-9][0-9]*$/
          const pattern = new RegExp(reg)
          if (!pattern.test(stockTotal)) {
            this.$message({
              type: 'error',
              message: '请正确输入库存'
            })
            return false
          }
        }
        return true
      },
      // 上传淘宝商品压缩包
      beforeZipUpload(file) {
        if (file.size / 1024 / 1024 > 50) {
          this.$message.error('上传文件大小不能超过50MB!')
        }
        this.fileLoading = true
        return true
      },
      handleUploadZipSuccess(res, file) {
        if (res.code === 101) {
          this.uploadCheckId = res.data
          this.checkUploadTaoBaoZip()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      checkUploadTaoBaoZip() {
        checkUploadTaoBaoZip(this.uploadCheckId).then(response => {
          if (response.isError) return
          if (response.data * 1 === 1) {
            this.fileLoading = false
            this.$message.success('上传成功')
            this.initGoodsList()
          } else {
            setTimeout(() => {
              this.checkUploadTaoBaoZip()
            }, 3000)
          }
        })
      },
      // 打开批量导入商品视图
      openImportGoods() {
        const routeData = this.$router.resolve({
          path: '/goods/import-goods/index',
          query: {}
        })
        window.open(routeData.href, '_blank')
      },
      openBatchSetGoodsCustomsGoodsCode() {
        this.setSearchListQuery()
        this.$refs.batchSetCustomsGoodsCodeRef.open(this.searchListQuery)
      },
      handleBatchSetCustomsGoodsCodeSuccessCall() {
        this.initGoodsList()
      },
      openBatchSetGoodsCategory() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.msgError('请勾选商品!')
          return
        }
        var supplierGoodsId = []
        this.multipleSelection.forEach((item) => {
          supplierGoodsId.push(item.supplierGoodsId)
        })
        this.$refs.batchSetSupplierGoodsCategoryRef.open(supplierGoodsId)
      },
      handleBatchSetGoodsCategorySuccessCall() {
        this.initGoodsList()
      },
      // 获取系统参数
      initEnterpriseConfig() {
        getByEnterpriseId(this.getEnterpriseId()).then((response) => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      }
    }
  }
</script>
<style lang="less" scoped>
  .top-operate {
    margin-bottom: 0;
  }

  .search-item {
    display: flex;
    align-items: center;
    padding-bottom: 15px;
    border-bottom: solid 1px #E4E7ED;

    >div,
    .el-cascader {
      margin-right: 10px;
    }

    .el-input {
      width: 300px;
    }
  }

  .btn-search {
    height: 60px;
    display: flex;
    align-items: center;
  }

  .user-avatar {
    width: 90px;
    height: 90px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  .category-style {
    color: #3abbdb;
  }

  .gray-bar {
    background: #e4e4e4;
    padding: 20px;
    margin-bottom: 20px;
    width: 80%;
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }
</style>
